package com.ymatou.iapi.productmanager.compare.publish;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ymatou.iapi.productmanager.compare.oldapi.OldGetProductCatalogInfosCall;
import com.ymatou.iapi.productmanager.compare.publish.bean.productAndCatalogInfo.ProductAndCatalogInfoBean;
import com.ymatou.iapi.productmanager.compare.publish.bean.productCatalogInfo.ProductcataloginfoReponse;
import com.ymatou.iapi.sellerproduct.service.GetProductAndCatalogInfoCall;
import com.ymatou.iapi.sellerproduct.service.ModifyReadyPutawayProductInfoV2Call;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.database.annotation.SqlMapperFactory;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.compare.AssertHelper;
import com.ymttest.utils.compare.LogPathConf;
import com.ymttest.utils.compare.LoggerHelper;
import com.ymttest.utils.compare.LoggerInterface;
import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class ModifyAppProductCompare {
	private final static Integer sellerId = 20362855;
	private final static String sellerName = "fyftest";
	private final static LogPathConf logPathConf = new LogPathConf(false);
	private final static LoggerInterface logger = new LoggerHelper(logPathConf);
	
	public static void compareModifyAppProduct(String fileName,JSONObject request){
		int addProductCatalogCount = initAndUpdateRequest(request);
		
		Pair<String,List<String>> old_productAndCatalogs = addProduct(addProductCatalogCount);
		YMTDateUtil.waitTime(2);
		Pair<String,List<String>> new_productAndCatalogs = addProduct(addProductCatalogCount);
		
		ModifyReadyPutawayProductInfoV2Call modifyProdCall = new ModifyReadyPutawayProductInfoV2Call();
		
		//call old
		String old_msg = "";
		try {
			setProductAndCatalogs(fileName,request,old_productAndCatalogs);
			JSONObject ret = modifyProdCall.callAndGetReturnData(request);
			old_msg = ret.getString("Msg");
		} catch (JSONException e) {
			logger.failure(fileName + "," + old_msg, e);
			return;
		}
		if (!old_msg.equals("")){
			logger.failure(fileName + "," + old_msg);
			return;
		}

		// call new
		String new_msg = "";
		try {
			request.put("TurnTo", "java");
			setProductAndCatalogs(fileName,request,new_productAndCatalogs);
			JSONObject ret = modifyProdCall.callAndGetReturnData(request);
			new_msg = ret.getString("Msg");
		} catch (JSONException e) {
			logger.failure(fileName + "," + new_msg, e);
			return;
		}

		if (!new_msg.equals("")){
			logger.failure(fileName + "," + new_msg);
			return;
		}
		
		checkProductCatalogInfos(fileName, old_productAndCatalogs.getLeft(), new_productAndCatalogs.getLeft());
		checkProductAndCatalogInfo(fileName, old_productAndCatalogs.getLeft(), new_productAndCatalogs.getLeft());
		
		
	}
	public static void setProductAndCatalogs(String fileName,JSONObject request,Pair<String,List<String>> productAndCatalogs){
		String productId = productAndCatalogs.getLeft();
		List<String> catalogs = productAndCatalogs.getRight();
		
		try {
			request.put("ProductId", productId);
			JSONArray catalogAry = request.getJSONArray("NewCatalogs");
			
			int k=0;
			for(int i=0;i<catalogAry.length();i++){
				JSONObject catalogNode = catalogAry.getJSONObject(i);
				if (!catalogNode.isNull("CatalogId")&&!catalogNode.getString("CatalogId").equals("")){
					catalogNode.put("CatalogId", catalogs.get(k));
					k=k+1;
				}
			}
			
			
		} catch (JSONException e) {
			logger.failure(fileName + ",setProductAndCatalogs", e);
		}
		
		
		
		
	}
	
	
	public static Pair<String,List<String>> addProduct(int addProductCatalogCount){
		try{
		
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc9.json");
			
			JSONArray CatalogListBean = addProductBean.getJSONObject("Product").getJSONArray("Catalogs");
			JSONObject CatalogFirst = CatalogListBean.getJSONObject(0);
			for(int i=1;i<addProductCatalogCount;i++){
				CatalogListBean.put(i, new JSONObject(CatalogFirst.toString()));
				
				CatalogListBean.getJSONObject(i).getJSONArray("PropertyValues").getJSONObject(1).getJSONArray("PropertyValues").getJSONObject(0).put("PropertyValue",String.valueOf(100+i));
			}
			
			
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID",sellerId,"LoginID",sellerName));
			String productId = SellerProductCallService.addNewProduct(addProductBean).getJSONObject("Data").getString("ProductID");
			
			List<String> catalogIds = SqlMapperFactory.getIntergratedProductMapper().selectCatalogsByProdId(productId)
														  .stream().map(x->x.get("sCatalogId").toString())
														  .collect(Collectors.toList());
			
			return Pair.of(productId, catalogIds);
			
		}catch(Exception e){
			logger.failure("addProduct",e);
		}
		return null;
	}
	
	
	public static void checkProductCatalogInfos(String fileName,String oldProd,String newProd){
		OldGetProductCatalogInfosCall oldCatalogInfoCall = new OldGetProductCatalogInfosCall();
		try{
			String desc = "File Name"+fileName+",ApiName: " + oldCatalogInfoCall.getApiName() + ", old product:" + oldProd+", new product:"+newProd;
			
			JSONObject oldRet = oldCatalogInfoCall.call(sellerId, oldProd,0);
			JSONObject newRet = oldCatalogInfoCall.call(sellerId, newProd,0);
			
			
			if (oldRet.isNull("Data")&&newRet.isNull("Data")){
				logger.verifyEquals(true, true, desc+",new return and old return are all null");
				return;
			}else if (!oldRet.isNull("Data")&&newRet.isNull("Data")){
				logger.failure(desc+",new return is null and old is not null");
				return;
			}else if (oldRet.isNull("Data")&&!newRet.isNull("Data")){
				logger.failure(desc+",old return is null and new is not null");
				return;
			}
			
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
			JSONObject oldData = oldRet.getJSONObject("Data");
			JSONObject newData = newRet.getJSONObject("Data");
			ProductcataloginfoReponse oldBean = gson.fromJson(oldData.toString(), ProductcataloginfoReponse.class);
			ProductcataloginfoReponse newBean = gson.fromJson(newData.toString(), ProductcataloginfoReponse.class);
			AssertHelper.assertResultEqual(oldBean,newBean,desc);
		}catch(Exception e){
			logger.failure(fileName+",checkProductCatalogInfos", e);
		}
	}
	
	
	
	private static void checkProductAndCatalogInfo(String fileName,String oldProd,String newProd) {
		GetProductAndCatalogInfoCall oldGetProductAndCatalogInfoCall = new com.ymatou.iapi.sellerproduct.service.GetProductAndCatalogInfoCall();
		try{
			String desc = "File Name"+fileName+",ApiName: " + oldGetProductAndCatalogInfoCall.getApiName() + ", old product:" + oldProd+", new product:"+newProd;
			
			JSONObject oldRet = oldGetProductAndCatalogInfoCall.callAndGetReturnData(sellerId, oldProd);
			JSONObject newRet = oldGetProductAndCatalogInfoCall.callAndGetReturnData(sellerId, newProd);
			
			
			if (oldRet.isNull("Data")&&newRet.isNull("Data")){
				logger.verifyEquals(true, true, desc+",new return and old return are all null");
				return;
			}else if (!oldRet.isNull("Data")&&newRet.isNull("Data")){
				logger.failure(desc+",new return is null and old is not null");
				return;
			}else if (oldRet.isNull("Data")&&!newRet.isNull("Data")){
				logger.failure(desc+",old return is null and new is not null");
				return;
			}
			
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
			JSONObject oldData = oldRet.getJSONObject("Data");
			JSONObject newData = newRet.getJSONObject("Data");
			ProductAndCatalogInfoBean oldBean = gson.fromJson(oldData.toString(), ProductAndCatalogInfoBean.class);
			ProductAndCatalogInfoBean newBean = gson.fromJson(newData.toString(), ProductAndCatalogInfoBean.class);
			logger.verifyEquals(oldBean.getProductAndCatalogInfoOnSellerProduct().getCatalogInfos().size(), 
					newBean.getProductAndCatalogInfoOnSellerProduct().getCatalogInfos().size(), desc);
			AssertHelper.assertResultEqual(oldBean,newBean,desc);
		}catch(Exception e){
			logger.failure(fileName+",checkProductAndCatalogInfo",e);
		}
	}
	
	
	
	
	
	//解析要发布的商品有几个规格
	public static int initAndUpdateRequest(JSONObject request){
		//set logger
		AssertHelper.setLoggerInterface(logger);
		
		//update sellerId and stock;
		try {
			request.put("UserId", sellerId);
			
			int addCount = 0;
			JSONArray catalogAry = request.getJSONArray("NewCatalogs");
			for (int i=0;i<catalogAry.length();i++){
				catalogAry.getJSONObject(i).put("Num", (i+1)*10);
				catalogAry.getJSONObject(i).put("PurchasedNum", (i+1)*10);
				catalogAry.getJSONObject(i).put("Price", 20000);
				addCount = addCount + 1;
			}
			
			JsonBeanHelper.updateJsonBean(request, MapUtil.hashMap("Brand->BrandId",13758,"Brand->BrandName","Air Jordan",
				"SecondCategoryId",1420,"ThirdCategoryId",1460));
		
			return addCount;
		}catch (JSONException e) {
			logger.failure("initAndUpdateRequest", e);
		}
		return 1;
	}
	
	
	
	public static void startCompareModifyAppProduct(){
		String folder = "json_app_modify";
		String fullPath = JsonBeanHelper.JsonBeanFileFolder + File.separator + folder;
		File f = new File(fullPath);
		File file[] = f.listFiles();
		for(int i=0;i<file.length;i++){
			String fileName = file[i].getName();
			System.out.println(fileName);
			try{
				JSONObject request =  JsonBeanHelper.getJsonBean(folder+File.separator+fileName);
				compareModifyAppProduct(fileName,request);
			}catch(Exception e){
				logger.failure(fileName,e);
			}
			
			
		}
		
	}
	
	
	
	public static void main(String arg[]) throws Exception{

	}
	
	
	
}
